package ar.edu.itba.twiteros.util;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
import ar.edu.itba.twiteros.dao.UserDao;
import ar.edu.itba.twiteros.domain.UserIds;

public class GrantTwitterAccess {

	private static String consumerKey="k7o1ugNpJ5XNH8iKrDlQ";
	
	private static String consumerSecret="BgxyJ3H4pwSZ5fxGNMABbt3Ss8J8c5ypVP6FchxA3cw";
	
	private Twitter twitter;
	
	private Long uid;
	
	
	public GrantTwitterAccess(Twitter twitter, Long uid){
		this.twitter= twitter;
		this.uid= uid;
		this.twitter.setOAuthConsumer(consumerKey, consumerSecret);
	}


	public static String getConsumerKey() {
		return consumerKey;
	}


	public static void setConsumerKey(String consumerKey) {
		GrantTwitterAccess.consumerKey = consumerKey;
	}

	
	public Long getUid() {
		return uid;
	}


	public void setUid(Long uid) {
		this.uid = uid;
	}


	public static String getConsumerSecret() {
		return consumerSecret;
	}


	public static void setConsumerSecret(String consumerSecret) {
		GrantTwitterAccess.consumerSecret = consumerSecret;
	}


	public Twitter getTwitter() {
		return twitter;
	}


	public void setTwitter(Twitter twitter) {
		this.twitter = twitter;
	}
	
	public boolean hasAcces(){
		boolean ans=false;
		UserIds user= UserDao.getUser(uid);
		
		if(user!=null){
			
			AccessToken pp= new AccessToken(user.getToken(), user.getTokenSecret());
			twitter.setOAuthAccessToken(pp);
			try {
				if(twitter.test()){
					ans=true;
				}
			} catch (TwitterException e) {

			}
		}
		
		return ans;
	}
	
	public boolean setAccessToken(){
		boolean ans=false;
		UserIds user= UserDao.getUser(uid);
		
		if(user!=null){
			if(user.isAccess()){
				AccessToken pp= new AccessToken(user.getToken(), user.getTokenSecret());
				twitter.setOAuthAccessToken(pp);
				ans=true;
			}
		}
		
		return ans;
	}
	
	public String getUrl(){
		RequestToken requestToken;
		try {
			requestToken = twitter.getOAuthRequestToken();
		} catch (TwitterException e) {
			return e.getMessage();
		}
		String token=  requestToken.getToken();
		String tokenSecret= requestToken.getTokenSecret();
		UserIds user= UserDao.getUser(uid);
		if(user==null){
			user=new UserIds(uid, token, tokenSecret);
		}else{
			user.setToken(token);
			user.setTokenSecret(tokenSecret);
		}
		UserDao.save(user);
		return requestToken.getAuthenticationURL();
	}
	
	
}
